package android_design_mode.chapter10_interpreter.interpreter001;

import android_design_mode.chapter10_interpreter.interpreter001.oprators.AdditionExpression;
import android_design_mode.chapter10_interpreter.interpreter001.oprators.SubtractionExpression;

import java.util.Stack;

public class Calculator {

    private Stack<ArithmeticExpression> mExpStack = new Stack<>();

    public Calculator(String expression) {

        ArithmeticExpression exp1, exp2;

        String[] elements = expression.split(" ");

        for (int i = 0; i < elements.length; i++) {
            String item = elements[i];
            switch (item.charAt(0)) {
                case '+':
                    exp1 = mExpStack.pop();
                    exp2 = new NumExpression(Integer.valueOf(elements[++i]));
                    mExpStack.push(new AdditionExpression(exp1, exp2));
                    break;
                case '-':
                    exp1 = mExpStack.pop();
                    exp2 = new NumExpression(Integer.valueOf(elements[++i]));
                    mExpStack.push(new SubtractionExpression(exp1, exp2));
                    break;
                default:
                    mExpStack.push(new NumExpression(Integer.valueOf(item)));
                    break;
            }
        }
    }

    public int calculate() {
        return mExpStack.pop().interpret();
    }
}
